#include "BlackScholes.h"

/* Returns the price of an option based on the Black-Scholes formula */
double ModelBlackScholes(int call, double S0, double K, double sigma, 
double T, double r, double divr) 
{

  if (!call) return ModelBlackScholes(CALL, S0, K, sigma, T, r, divr) - S0 
+ K*exp(-r*T);

  double d1 = (log(S0*exp(-divr*T)/K) + (r + sigma*sigma/2)*T)/(sigma*sqrt(T));
  double d2 = d1 - sigma*sqrt(T);

  return (S0*exp(-divr*T)*ModelCumNormal(d1) - K*exp(-r*T)*ModelCumNormal(d2));

}



double A[5] = {0.319381530, -0.356563782, 1.78147793, -1.821255973, 1.330274429};


/* Returns the pdf for the normal distribution. */

double NPrime(double x)
{
  return ( M_2_SQRTPI/(2*M_SQRT2) * exp(-x*x/2) );
}

/* Returns the cdf for the normal distribution. */

double ModelCumNormal(double x)
{
  if ( x < 0 ) return ( 1 - ModelCumNormal(-x) );

  double k = 1/(1 + G*x);
  double S = 0;
	  
  int i = 0;
  double j = k;

  for(i = 0; i < 5; i++) {
    S += A[i]*j;
    j *= k;
  }

  return ( 1 - NPrime(x)*S );
}
